package hhf.flex.soundapi.ui {
	import flash.display.Graphics;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	import hhf.flex.soundapi.core.SoundEvent;
	
	import mx.core.Container;
	import mx.core.UIComponent;
	
	[Event(name="selectRange", type="hhf.flex.soundapi.core.SoundEvent")]
	[Event(name="unselectRange", type="hhf.flex.soundapi.core.SoundEvent")]
 	[Style(name="fillColor", type="uint", format="Color ", inherit="yes")]

	public class SelectionRange extends Container {
		private var begin:Number = 0;
		private var end:Number = 0;
		public function SelectionRange() {
			super();
			this.setStyle("fillColor", 0x00cc00);
			addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler);
		}
		
		public function reset():void {
			this.graphics.clear();
		}
		private var inDrag:Boolean = false;
		private function mouseDownHandler(event:MouseEvent):void {
			addEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
			addEventListener(MouseEvent.MOUSE_OUT, mouseUpHandler);
			addEventListener(MouseEvent.MOUSE_MOVE, mouseDragHandler);
			addEventListener(Event.ENTER_FRAME, enterFrame);
			begin = event.localX;
			end = event.localX;
		}

		private function mouseDragHandler(event:MouseEvent):void {
			end = event.localX;
		}
		private function mouseUpHandler(event:MouseEvent):void {
			removeEventListener(MouseEvent.MOUSE_UP, mouseUpHandler);
			removeEventListener(MouseEvent.MOUSE_OUT, mouseUpHandler);
			removeEventListener(MouseEvent.MOUSE_MOVE, mouseDragHandler);
			removeEventListener(Event.ENTER_FRAME, enterFrame);
			var start:Number = Math.min(begin, end)*100/this.width;
			var stop:Number = Math.max(begin, end)*100/this.width;
			if(begin == end) {
				reset();
				dispatchEvent(new SoundEvent(SoundEvent.UNSELECTRANGE));
			} else {
				trace("start : "+start+"%");
				trace("stop : "+stop+"%");
				dispatchEvent(new SoundEvent(SoundEvent.SELECTRANGE, start, stop));
			}
		}

		private function enterFrame(event:Event):void {
			var g:Graphics = this.graphics; 
			g.clear();
			g.lineStyle(1, getStyle("fillColor"));
			g.beginFill(getStyle("fillColor"), 0.05);
			g.drawRect(begin, 0, end-begin, this.height);
		}

	}
}